<template>
	<view class="install-equipment">
		<view class="flex-row form-input">
			设备序列号
			<input :value="serialNumber" disabled class="input-box" type="text" placeholder="请输入设备序列号" />
		</view>
		<view class="flex-row form-input">
			机箱序列号
			<input :value="chassisNumber" @click="scanCodeInfo" disabled class="input-box" type="text" placeholder="请输入机箱序列号" />
			<uni-icons type="scan" @click="scanCodeInfo" size="20"></uni-icons>
		</view>
		<view class="selection-box flex-row form-input">
			地址/区域
			<view :class="['selection', !formFields.region && 'empty']" @click="chooseLocation">
				{{ formFields.region || '请选择' }}
			</view>
			<text class="iconfont icon-arrow-right"></text>
		</view>
		<view class="label">详细地址</view>
		<view class="form-textarea">
			<textarea v-model="formFields.address" class="textarea-box" placeholder="请输入详细地址" />
		</view>
		<view class="label">
			添加照片
			<text style="color: #999; font-size: 26rpx">正面/侧面/门头/远景</text>
		</view>
		<view class="grid-box">
			<view v-for="(img, index) in uploadImgs" :key="img" class="grid-item">
				<image class="cover-image" :src="img" mode="aspectFill" @click="previewImage(img)" />
				<text class="iconfont icon-close" @click="handleDeleteImg(index)"></text>
			</view>
			<view v-if="uploadImgs.length < 4" class="grid-item upload-box flex align-center justify-center" @click="uploadImgsHandler"></view>
		</view>
		<button class="btn-primary btn-submit" @click="handleSubmit">提交</button>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { previewImage, uploadFile } from '@/utils';
import { fetchDeviceInfo, fetchDeviceInstall } from '@/api';
import { useUserStore } from '@/store/user';
import { getURLQuery } from '@/utils';

const userStore = useUserStore();

const uploadImgs = ref([]);

const formFields = reactive({
	region: '',
	address: '',
	longitude: 0,
	latitude: 0
});

const serialNumber = ref('');
const chassisNumber = ref('');
const chassisConfig = ref([])

onLoad((e) => {
	serialNumber.value = e?.serialNum;
	fetchDeviceInfo(e?.serialNum).then((res) => {
		// if (res.cha_serial_no) chassisNumber.value = res.cha_serial_no;
		chassisConfig.value = res.cha_config
	});
	
});
const keyMap = {
	'01': 'product_identification',
	11: 'production_date',
	17: 'expiry_date',
	21: 'host_serial_no',
	91: 'other'
};
function scanCodeInfo() {
	uni.scanCode({
		success(res) {
			const { query: querys = '' } = getURLQuery(res.result);
			if (!querys)
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			const params = querys.split('(');
			const temp = {};
			for (const param of params) {
				const splitStr = param.split(')');
				const key = splitStr[0];
				if (key in keyMap) temp[keyMap[key]] = splitStr[1];
			}
			console.log(temp);
			if (!temp.host_serial_no)
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			if(!temp.other){
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			}
			if(chassisConfig.value.indexOf(temp.other) == -1){
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			}else{
				chassisNumber.value = temp.host_serial_no
			}
		}
	});
}
function handleSubmit() {
	const showMsg = (title) => uni.showToast({ title, icon: 'none' });
	if (!formFields.region) return showMsg('请选择地址');
	if (!formFields.address) return showMsg('请填写详细地址');
	if (uploadImgs.value.length < 4) return showMsg('请上传完四个角度的照片');
	const params = {
		// 设备序列号
		host_serial_no: serialNumber.value,
		img: uploadImgs.value.join('|'),
		user_id: userStore.userInfo.id,
		...formFields
	};
	if (!!chassisNumber.value) params['cha_serial_no'] = chassisNumber.value;
	uni.showModal({
		title: '温馨提示',
		content: '确认安装当前设备吗？',
		confirmColor: '#377DFF',
		success(res) {
			res.confirm &&
				fetchDeviceInstall(params).then(() => {
					showMsg('已提交');
					setTimeout(uni.navigateBack, 1000);
				});
		}
	});
}
function chooseLocation() {
	uni.chooseLocation({
		success(res) {
			formFields.region = res.address + res.name;
			formFields.latitude = res.latitude;
			formFields.longitude = res.longitude;
		},
		fail() {
			uni.showToast({
				title: '地址选择失败！',
				icon: 'error'
			});
		}
	});
}

function handleDeleteImg(index) {
	uni.showModal({
		title: '提示',
		content: '确定删除图片吗？',
		confirmColor: '#377DFF',
		success(res) {
			if (res.confirm) {
				uploadImgs.value.splice(index, 1);
			}
		}
	});
}

function uploadImgsHandler() {
	uni.chooseImage({
		count: 4 - uploadImgs.value.length,
		sourceType: ['camera'],
		success: (chooseImageRes) => {
			const tempFilePaths = chooseImageRes.tempFilePaths;
			for (const path of tempFilePaths) {
				uploadFile(path).then((res) => {
					uploadImgs.value.push(res);
				});
			}
		}
	});
}
</script>

<style scoped lang="scss">
.install-equipment {
	padding: 20rpx 30rpx;
	.form-input {
		min-height: 100rpx;
		border-bottom: 2rpx solid #efefef;
		.empty {
			color: #999;
		}
		.input-box {
			text-align: right;
		}
	}
	.selection-box {
		padding: 30rpx 0;
		box-sizing: border-box;
	}
	.selection {
		flex: 1;
		margin-left: 20rpx;
		margin-right: 20rpx;
		text-align: right;
	}
	.label {
		padding-top: 40rpx;
		padding-bottom: 24rpx;
	}
	.form-textarea {
		height: 230rpx;
		padding: 30rpx;
		border-radius: 8rpx;
		box-sizing: border-box;
		background-color: #efefef;
		.textarea-box {
			height: 100%;
		}
	}
	.grid-box {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		gap: 30rpx;
		.grid-item {
			height: 200rpx;
			border-radius: 10rpx;
			overflow: hidden;
			position: relative;
			.cover-image {
				width: 100%;
				height: 100%;
			}
			.icon-close {
				position: absolute;
				right: 10rpx;
				top: 10rpx;
				color: #fff;
				font-size: 20rpx;
				border-radius: 50%;
				padding: 10rpx;
				background-color: $red-color;
			}
		}
		@mixin addIcon {
			content: '';
			position: absolute;
			background-color: #b1b1b1;
		}
		.upload-box {
			background-color: #efefef;
			position: relative;
			&::before {
				width: 110rpx;
				height: 2rpx;
				@include addIcon();
			}
			&::after {
				width: 2rpx;
				height: 110rpx;
				@include addIcon();
			}
		}
	}
	.btn-submit {
		margin: 60rpx 0;
	}
}
</style>
